import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/shoping_cart/model/shopping_cart_provider.dart';
import 'package:flutter_provider_demo/shoping_cart/shopping_cart_page.dart';
import 'package:flutter_provider_demo/shopping/model/shopping_provider.dart';
import 'package:provider/provider.dart';

class ShoppingPage extends StatefulWidget {
  ShoppingPage({Key key}) : super(key: key);

  @override
  _ShoppingPageState createState() => _ShoppingPageState();
}

class _ShoppingPageState extends State<ShoppingPage> {
  @override
  Widget build(BuildContext context) {
    var shoppingCartProvider = context.watch<ShoppingCartProvider>();

    return Scaffold(
      appBar: AppBar(
        title: Text('商品'),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (_) => ShoppingCartPage()));
            },
            icon: Icon(Icons.shopping_cart),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('${shoppingCartProvider.items.length}件'),
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (_) => ShoppingCartPage()));
        },
      ),
      body: ListView.builder(
          itemCount: context.watch<ShoppingProvider>().length,
          itemBuilder: (_, index) => ShoppingItem(index: index)),
    );
  }
}

class ShoppingItem extends StatelessWidget {
  const ShoppingItem({Key key, this.index}) : super(key: key);

  final int index;

  @override
  Widget build(BuildContext context) {
    var textTheme = Theme.of(context).textTheme.headline6;

    var item = context
        .select<ShoppingProvider, Item>((model) => model.getByPosition(index));

    var isInCart = context.select<ShoppingCartProvider, bool>((model) {
      return model.items.contains(item);
    });

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: LimitedBox(
        maxHeight: 48,
        child: Row(
          children: [
            AspectRatio(
              aspectRatio: 1,
              child: Container(
                color: item.color,
              ),
            ),
            SizedBox(
              width: 20,
            ),
            Expanded(
              child: Text(item.name, style: textTheme),
            ),
            SizedBox(
              width: 20,
            ),
            FlatButton(
              onPressed: isInCart
                  ? () => context.read<ShoppingCartProvider>().remove(item)
                  : () => context.read<ShoppingCartProvider>().add(item),
              child: isInCart ? Icon(Icons.check) : Text('添加'),
            ),
          ],
        ),
      ),
    );
  }
}
